<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              <div>
                {{ formatEmployment(scope.row.formOfEmployment) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/details')">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <!-- 分页组件 -->
            <el-pagination
              layout="total, sizes,prev, pager, next, jumper"
              :total="total"
              :page-size="size"
              :page-sizes="[2,5,10]"
              @current-change="hCurrentChange"
              @size-change="hSizeChange"
            />
          </el-row>
        </el-row>
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      title="新增员工"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="hCloseDialog"
    >
      <empe-dialog ref="AddEmployee" @close="showDialog=false" @update-empolyee="hUpdateEmpolyee" />
    </el-dialog>
    <!-- 分配角色弹框 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
    >
      <assign-role v-if="showDialogRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
    </el-dialog>
  </div>

</template>
<script>
import AssignRole from './assignRole'
import imageHolder from './imgHolder.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import empeDialog from './empeDialog.vue'
const hireType = EmployeeEnum.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})
export default {
  components: { empeDialog, imageHolder, AssignRole },

  data() {
    return {
      showDialogRole: false,
      list: [],
      page: 1, // 当前页码
      size: 5, // 每页几条
      total: 0, // 总的数据条数
      showDialog: false,
      curEmployeId: '', // 当前的员工编号
      curPage: 1
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
        this.curPage = this.page // 通知分页组件去更新页码数据
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    formatEmployment(id) {
      return hireType[id]
    },

    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')
        if (this.roles.length === 0) {
          this.pageParams.page--
          if (this.pageParams.page < 1) {
            this.pageParams.page = 1
          }
        }
        // 2. 重新请求
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 关闭弹层
    // 1. 在表单中点击取消（添加成功）
    // 2. 弹层上点击 X
    hCloseDialog() {
      // 相当于是在父组件中去执行子组件中方法
      // 去清空 子组件中的表单数据和校验结果
      // 子组件.resetForm()
      // console.log('在父组件中获取子组件的引用', this.$refs.AddEmployee)
      this.$refs.AddEmployee.resetForm()
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      if (this.total % this.size === 0) {
        this.total++
        this.page = (this.total / this.size) + 1
      } else {
        // 最后一页的页码
        this.page = Math.floor(this.total / this.size) + 1
      }
      this.loadEmployeeList()
    },
    formatDate(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log('做格式转换', rows)
      /** *
       * rows:
       * [
       *  {mobile:'13612345678', username:'管理员'.....}
       *  {mobile:'13612545678', username:'小王'.....}
       * ]
       *
       *
       *
       *  header:  [手机, 用户名]
       *  data: [ ['13612345678', '管理员'], ['13612545678', '小王'] ]
       */
      // 把英文的key转成中文的表头
      const enKeys = Object.keys(rows[0])

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => {
        return Object.values(obj)
      })
      console.log(enKeys, header, data)

      return {
        header,
        data // [ ['13612345678', '管理员'], [] ]
      }
    },
    // 导出
    async hExportExcel() {
      // 1. 求数据
      const res = await getEmployeeList(this.pageParams)
      console.log('员工信息是', res.data.rows)
      // 2. 做格式转换
      const { header, data } = this.formatDate(res.data.rows)
      console.log('结果', header, data)
      // 3. 调用Export2Excel保存数据到excel

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '123', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 用户点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true

      this.curEmployeId = id
    }
  }
}
</script>
